package com.example.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Charge;
import com.example.entity.Dorm;
import com.example.entity.Student;
import com.example.exception.CustomException;
import com.example.mapper.DormMapper;
import com.example.service.ChargeService;
import com.example.service.StudentService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电费缴费信息表前端操作接口
 **/
@RestController
@RequestMapping("/charge")
public class ChargeController {

    @Resource
    private ChargeService chargeService;

    @Resource
    private StudentService studentService;

    @Resource
    private DormMapper dormMapper;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Charge charge) {
        chargeService.add(charge);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        chargeService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        chargeService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody Charge charge) {
        chargeService.updateById(charge);
        return Result.success();
    }

    /**
     * 缴费
     */
    @PutMapping("/pay")
    public Result payById(@RequestBody Charge charge) {
        chargeService.payById(charge);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Charge charge = chargeService.selectById(id);
        return Result.success(charge);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Charge charge ) {
        List<Charge> list = chargeService.selectAll(charge);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Charge charge,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Charge> page = chargeService.selectPage(charge, pageNum, pageSize);
        return Result.success(page);
    }

    @GetMapping("/getPie/{time}")
    public Result getPie(@PathVariable("time")String time) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Charge charge = new Charge();
        // 根据学生权限不同判断
        Account currentUser = TokenUtils.getCurrentUser();
        if(currentUser.getRole().equals(RoleEnum.STUDENT.name())){
            // 查询学生是否绑定宿舍
            Student student = studentService.selectById(currentUser.getId());
            if(ObjectUtil.isNull(student)){
                throw new CustomException("500","学生不存在");
            }
            if(student.getDormId() != null){
                charge.setDormId(student.getDormId());
            }
            // 如果没有传时间，默认当月
            if(StringUtils.isBlank(time)){
                charge.setTime(new SimpleDateFormat("yyyy-MM").format(new Date()));
            }else {
                charge.setTime(time);
            }
            List<Charge> all = chargeService.selectAll(charge);
            Map<String, List<Charge>> collect = all.stream().collect(Collectors.groupingBy(Charge::getStatus));
            for (String key : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", key);
                map.put("value", collect.get(key).get(0).getAmount());
                list.add(map);
            }
            resultMap.put("text", "缴费情况统计图（饼图）");
            resultMap.put("subtext", "统计维度：缴费年月");
            resultMap.put("name", "缴费费用");
            resultMap.put("data", list);
        }else {
            // 如果没有传时间，默认当月
            if(StringUtils.isBlank(time)){
                charge.setTime(new SimpleDateFormat("yyyy-MM").format(new Date()));
            }else {
                charge.setTime(time);
            }
            List<Charge> all = chargeService.selectAll(charge);
            Map<Integer, List<Charge>> collect = all.stream().collect(Collectors.groupingBy(Charge::getDormId));
            for (Integer key : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                Dorm dorm = dormMapper.selectById(key);
                map.put("name", dorm.getName());
                map.put("value", collect.get(key).get(0).getAmount());
                list.add(map);
            }
            resultMap.put("text", "缴费情况统计图（饼图）");
            resultMap.put("subtext", "统计维度：缴费年月");
            resultMap.put("name", "缴费费用");
            resultMap.put("data", list);
        }
        return Result.success(resultMap);
    }

}